import axios  from "axios";

function getPolygonInstance(py, option,height) {
    let positions = Cesium.Cartesian3.fromDegreesArrayHeights(py.pts);
    let holes = [];
    for (let m = 0; m < py.holes.length; m++) {
        holes.push({positions: Cesium.Cartesian3.fromDegreesArray(py.holes[m])});
    }

    let polygonInstance = new Cesium.GeometryInstance({
        geometry: new Cesium.PolygonGeometry({
            polygonHierarchy: {
                positions: positions,
                holes: holes
            },
            height: height
        }),
        attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString(option.fillColor).withAlpha(option.fillOpacity))
        }
    });

    return polygonInstance;
}

export function changeRiverWater(viewer,type){
  //先清除
  clearAll()
  addRiverWater(viewer,type,true)
}

let xiangjiang;
let BaiShiGangDown;
let primitive;
export function addRiverWater(viewer,type,ischange = false){
    //type 0 建港后  1 建港前
    axios.get(`data/河流面${type === 0 ? '':'-no'}.json`).then((data)=>{
      
      var geojson = new Cesium.Geojson();
      geojson = geojson.read(data.data);
      var option = option ? option : {};
      option.asynchronous = option.asynchronous ? option.asynchronous : false;
      option.clampToGround = option.clampToGround ? option.clampToGround : false;
      option.fillColor = option.fillColor ? option.fillColor : '#ff0000';
      option.fillOpacity = option.hasOwnProperty('fillOpacity') ? option.fillOpacity : 1.0;
      option.pixelSize = option.pixelSize ? option.pixelSize : 10;
      option.strokeColor = option.strokeColor ? option.strokeColor : '#ff0000';
      option.strokeOpacity = option.hasOwnProperty('strokeOpacity') ? option.strokeOpacity : 1.0;
      option.lineWidth = option.hasOwnProperty('lineWidth') ? option.lineWidth : 2.0;
      option.outlineWidth = option.hasOwnProperty('outlineWidth') ? option.outlineWidth : 0;
      option.translucent = false;
      if (option.fillOpacity != 1.0 || option.strokeOpacity != 1.0) {
          option.translucent = true;
      }

      let polygonInstances = [];
      let instances1 = [];
      let instances2 = [];
      for (let i = 0; i < geojson.polygonArray.length; i++) {
          let item = geojson.polygonArray[i].geometry;
          if(i == 2){
              let instance = getPolygonInstance(item, option,39);
              polygonInstances.push(instance);
          }

          if(i == 1){
              let instance = getPolygonInstance(item, option, ischange ? 40 : 39);
              instances1.push(instance);
          }

          if(i == 0){
              let instance = getPolygonInstance(item, option,ischange ? 39 : 37);
              instances2.push(instance);
          }
      }

      xiangjiang =  addxiangjiang(viewer,instances1);
      BaiShiGangDown = addBaiShiGangDown(viewer,polygonInstances);
      primitive = addBaiShiGangUp(viewer,instances2);
      // startFloodUp(primitive);
      if(ischange){
        startFloodDown(primitive._waterEffect)
      }
    })
}

//加载白石岗上游水面
function addBaiShiGangUp(viewer,instances){
    const waterEffect = new Cesium.WaterEffect(viewer, {
        instances: instances,
        renderPass: [4]
    })
    waterEffect.showReflect = true;
    waterEffect.reflectHeight = 58;
    // waterEffect.appearance.material.uniforms.baseColor = Cesium.Color.fromCssColorString('#eae263');
    waterEffect.appearance.material.uniforms.baseColor = Cesium.Color.fromCssColorString('#E09464');
    waterEffect.appearance.material.uniforms.u_ReflectionStrength = 2.6;
    waterEffect.appearance.material.uniforms.u_WaterDepth = 0.1;
    waterEffect.appearance.material.uniforms.u_FoamIntersectionFade = 0.15;
    waterEffect.appearance.material.uniforms.u_causticScale = 0.0003;
    waterEffect.appearance.material.uniforms.u_FoamScale = 330;
    waterEffect.appearance.material.uniforms.u_causticIntersectionFade = 0.94;

    // waterEffect.appearance.material.uniforms.u_WaterDeepColor = Cesium.Color.fromCssColorString('#8967b5');
    // waterEffect.appearance.material.uniforms.u_HorizonColor = Cesium.Color.fromCssColorString('#7e712a');
    // waterEffect.appearance.material.uniforms.u_waterAngle  = 360;
    // waterEffect.appearance.material.uniforms.u_waterSpeed = 7000;
    return waterEffect;
}

//加载白石岗下游水面
function addBaiShiGangDown(viewer,instances){
    const waterEffect = new Cesium.WaterEffect(viewer, {
        instances:instances,
        // centerPos: Cesium.Cartesian3.fromDegrees(113.143452,27.801824,37.58664695001572),
        renderPass: [4]
    })

    waterEffect.showReflect = false;
    waterEffect.reflectHeight = 58;
    // waterEffect.appearance.material.uniforms.baseColor = Cesium.Color.fromCssColorString('#eae263');

    waterEffect.appearance.material.uniforms.baseColor = Cesium.Color.fromCssColorString('#E09464');

    waterEffect.appearance.material.uniforms.u_ReflectionStrength = 2.6;
    waterEffect.appearance.material.uniforms.u_WaterDepth = 0.1;
    waterEffect.appearance.material.uniforms.u_FoamIntersectionFade = 0.15;
    waterEffect.appearance.material.uniforms.u_causticScale = 0.0003;
    waterEffect.appearance.material.uniforms.u_FoamScale = 330;
    waterEffect.appearance.material.uniforms.u_causticIntersectionFade = 4.6;
    waterEffect.appearance.material.uniforms.oceanOneOverAmplitudeLowAltitude = 0.365;
    waterEffect.appearance.material.uniforms.oceanFrequencyLowAltitude = 2000;

    // waterEffect.appearance.material.uniforms.u_WaterDeepColor = Cesium.Color.fromCssColorString('#8967b5');
    // waterEffect.appearance.material.uniforms.u_HorizonColor = Cesium.Color.fromCssColorString('#7e712a');
    waterEffect.appearance.material.uniforms.u_waterAngle  = 360;
    waterEffect.appearance.material.uniforms.u_waterSpeed = 7000;
    
    return waterEffect;
}


function addxiangjiang(viewer,instances){
    const waterEffect = new Cesium.WaterEffect(viewer, {
        instances: instances,
        renderPass: [ 4]
    })

    waterEffect.showReflect = true;
    waterEffect.reflectHeight = 58;
    waterEffect.appearance.material.uniforms.u_WaterDepth = 0.5;
    waterEffect.appearance.material.uniforms.baseColor = Cesium.Color.fromCssColorString("#E0AD57");
    waterEffect.appearance.material.uniforms.u_noiseIntensity = 0.069;
    waterEffect.appearance.material.uniforms.u_WaterShallowColorAlpha = 1;
    waterEffect.appearance.material.uniforms.u_WaterDeepColorAlpha = 1;
    waterEffect.appearance.material.uniforms.u_FoamScale = 200;
    waterEffect.appearance.material.uniforms.u_ReflectionStrength = 1.4;
    waterEffect.appearance.material.uniforms.u_ReflectionMix = 0.38;
    waterEffect.appearance.material.uniforms.u_ReflectionFresnelPower = 0;
    waterEffect.appearance.material.uniforms.oceanAnimationSpeedLowAltitude = 0.0145; // 振幅
    waterEffect.appearance.material.uniforms.oceanFrequencyLowAltitude = 175366.455; // 密度


    waterEffect.appearance.material.uniforms.oceanOneOverAmplitudeLowAltitude = 2; // 浪高
    waterEffect.appearance.material.uniforms.oceanAnimationSpeedLowAltitude = 0.161;
    waterEffect.appearance.material.uniforms.u_FoamSpeed = 367;
    waterEffect.appearance.material.uniforms.u_FoamIntersectionFade = 0.02;
    waterEffect.appearance.material.uniforms.u_center.w = 4000;
    

    // const water = gui.addFolder('水面渲染');
    // water.add({ sun: 1 }, "sun", 0, 1, 0.1).name("光照亮度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.luminance = value
    // })
    // water.addColor({ color: "#fff" }, "color").name("基础颜色").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.baseColor = Cesium.Color.fromCssColorString(value)
    // })
    // water.add({ alpha: 0.8 }, "alpha", 0, 1, 0.1).name("透明度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.alpha = value
    // })
    // water.add({ alpha: 1000 }, "alpha", 1000, 100000, 1).name("lod距离").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_center.w = value
    // })
    // water.add({ u_WaterDepth: 0.4 }, "u_WaterDepth", 0, 30, 0.1).name("水深值").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_WaterDepth = value
    // })
    // water.add({ noiseIntensity: 0.1 }, "noiseIntensity", .0, 1, 0.001).name("扭曲度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_noiseIntensity = value;
    // })
    // water.addColor({ u_WaterShallowColor: "#fff" }, "u_WaterShallowColor").name("浅水区颜色").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_WaterShallowColor = Cesium.Color.fromCssColorString(value)
    // })
    // water.add({ u_WaterShallowColorAlpha: 0.38 }, "u_WaterShallowColorAlpha", 0, 1, 0.001).name("浅水区透明度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_WaterShallowColorAlpha = value
    // })
    // water.addColor({ u_WaterDeepColor: "#fff" }, "u_WaterDeepColor").name("深水区颜色").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_WaterDeepColor = Cesium.Color.fromCssColorString(value)
    // })
    // water.add({ u_WaterDeepColorAlpha: 0.8 }, "u_WaterDeepColorAlpha", 0, 1, 0.001).name("深水区透明度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_WaterDeepColorAlpha = value
    // })
    // water.addColor({ u_HorizonColor: "#fff" }, "u_HorizonColor").name("菲涅尔散射").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_HorizonColor = Cesium.Color.fromCssColorString(value)
    // })
    // water.add({ u_HorizonDistance: 6 }, "u_HorizonDistance", 0, 15, 0.01).name("菲涅尔系数").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_HorizonDistance = value
    // })
    // water.add({ enabled: true }, 'enabled').name("开启反射").onChange((value) => {
    //     waterEffect.showReflect = value;
    // });
    // water.add({ u_ReflectionStrength: 625 }, "u_ReflectionStrength", 10, 1000, 0.1).name("反射平面").onChange(function (value) {
    //     waterEffect.reflectHeight = value
    // })
    // water.add({ u_ReflectionStrength: 2.6 }, "u_ReflectionStrength", 0, 3, 0.01).name("反射强度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_ReflectionStrength = value
    // })
    // water.add({ u_ReflectionMix: 0.5 }, "u_ReflectionMix", 0, 1, 0.01).name("反射混合度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_ReflectionMix = value
    // })
    // water.add({ u_ReflectionFresnelPower: 4 }, "u_ReflectionFresnelPower", 0, 15, 0.01).name("反射菲涅尔系数").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_ReflectionFresnelPower = value
    // })
    // water.add({ u_FoamBlend: 0.63 }, "u_FoamBlend", 0, 1, 0.01).name("白浪混合度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_FoamBlend = value
    // })
    // water.add({ u_FoamSpeed: 120 }, "u_FoamSpeed", 60, 500, 0.01).name("白浪速度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_FoamSpeed = value
    // })
    // water.add({ u_FoamScale: 200 }, "u_FoamScale", 0.1, 500, 0.01).name("白浪缩放").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_FoamScale = value
    // })
    // water.add({ u_FoamIntersectionFade: 0.75 }, "u_FoamIntersectionFade", 0, 10, 0.01).name("白浪强度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_FoamIntersectionFade = value
    // })
    // water.add({ u_causticScale: 0.001 }, "u_causticScale", 0.0001, 1, 0.0001).name("焦散缩放").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_causticScale = value
    // })
    // water.add({ u_causticSpeed: 1 }, "u_causticSpeed", 60, 500, 0.01).name("焦散速度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_causticSpeed = value
    // })
    // water.add({ u_causticIntersectionFade: 8 }, "u_causticIntersectionFade", 0, 20, 0.01).name("焦散强度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_causticIntersectionFade = value
    // })
    // water.addColor({ u_causticColor: "#fff" }, "u_causticColor").name("焦散颜色").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.u_causticColor = Cesium.Color.fromCssColorString(value)
    // })
    // water.add({ oceanOneOverAmplitudeLowAltitude: 0.5 }, "oceanOneOverAmplitudeLowAltitude", .001, 2, 0.001).name("浪高").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.oceanOneOverAmplitudeLowAltitude = value;
    // })
    // water.add({ oceanAnimationSpeedLowAltitude: 0.4 }, "oceanAnimationSpeedLowAltitude", .001, 2, 0.001).name("振幅").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.oceanAnimationSpeedLowAltitude = value;
    // })
    // water.add({ oceanFrequencyLowAltitude: 825000 }, "oceanFrequencyLowAltitude", 2000, 1000000, 0.001).name("密度").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.oceanFrequencyLowAltitude = value;
    // })
    // water.add({ shiny: 800 }, "shiny", .001, 1000, 0.001).name("平滑").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.shiny = value;
    // })
    // water.add({ spec: 10.0 }, "spec", .001, 20, 0.001).name("高光").onChange(function (value) {
    //     waterEffect.appearance.material.uniforms.spec = value;
    // })

    return waterEffect
}

//更新水面水深的
function updateHeight(waterPrimitive, offsetHeight) {
    if(!waterPrimitive){
        console.log('=============');
    }
    const boundingSphere = waterPrimitive._boundingSpheres[0];
    if (!boundingSphere) {
        return;
    }

    let m = Cesium.Transforms.eastNorthUpToFixedFrame(boundingSphere.center);
    let inverse = Cesium.Matrix4.inverse(m, new Cesium.Matrix4());

    let mScale = Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(1.0, 1.0, offsetHeight));
    let tt = Cesium.Matrix4.multiply(mScale, inverse, new Cesium.Matrix4());
    waterPrimitive.modelMatrix = Cesium.Matrix4.multiply(m, tt, new Cesium.Matrix4());
}

let timer 
export function addArea(){
  startFloodUp(primitive._waterEffect);
}

export function downArea(){
   startFloodDown(primitive._waterEffect)
}

export function clearAll(){
  if(timer){
    clearInterval(timer)
    timer = null
  }
//   debugger
  if (xiangjiang) {
    xiangjiang&&xiangjiang._viewer.scene.primitives.remove(xiangjiang._waterEffect);
    xiangjiang&&xiangjiang._waterEffect.destroy();
    xiangjiang = null;
  }
  if (BaiShiGangDown) {
    BaiShiGangDown&&BaiShiGangDown._viewer.scene.primitives.remove(BaiShiGangDown._waterEffect);
    BaiShiGangDown&&BaiShiGangDown._waterEffect.destroy()
    BaiShiGangDown = null;
  }
  if (primitive) {
    primitive&&primitive._viewer.scene.primitives.remove(primitive._waterEffect);
    primitive&&primitive._waterEffect.destroy()
    primitive = null;
  }
//   primitive&&primitive.destroy()
}


//河水开始下降
 function startFloodDown(primitive){
  if(!primitive) return
    let topHeight = 36;
    let waterHeight = 44;
    let targetHeight = 36;
    let steep =  0.02;
    
    if(timer){
      clearInterval(timer)
      timer = null
    }
    // const startTime =new Date()
     timer = setInterval(() => {
        if (waterHeight > targetHeight) {
            waterHeight -= steep;
            if (waterHeight < targetHeight) {
                waterHeight = targetHeight;
            }
            updateHeight(primitive,waterHeight - topHeight);
        } else {
          // const endTime = new Date();
          // const executionTime = endTime - startTime;
          // console.log(executionTime,'time')
            clearInterval(timer);
        }
    }, 25);
}


//河水开始上涨
function startFloodUp(primitive){
  if(!primitive) return

    let topHeight = 36;
    let waterHeight = topHeight;
    let targetHeight = 43;
    let steep =  0.03;

    if(timer){
      clearInterval(timer)
      timer = null
    }

     timer = setInterval(() => {
        if (waterHeight < targetHeight) {
            waterHeight += steep;
            if (waterHeight > targetHeight) {
                waterHeight = targetHeight;
            }
            updateHeight(primitive,waterHeight - topHeight  );
        } else {
            clearInterval(timer);
        }
    }, 25);
}